package com.bdmc.smokesensor.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bdmc.smokesensor.Utils.Msg;
import com.bdmc.smokesensor.Utils.ResultUtil;
import com.bdmc.smokesensor.entity.Sys_Department;
import com.bdmc.smokesensor.entity.Sys_Log;
import com.bdmc.smokesensor.iservices.ISmk_GroupCompanyService;
import com.bdmc.smokesensor.iservices.ISys_DepService;
import com.bdmc.smokesensor.services.Sys_DepService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/dep", method = RequestMethod.POST)
public class Sys_DepController extends BaseController {

    @Autowired
    private ISys_DepService _depSvs;

    @Autowired
    private ISmk_GroupCompanyService _gcSvs;

    @RequestMapping(value = "/list")
    public Msg listPageable(@RequestBody Map<String, Integer> reqMap) {
        int depType = reqMap.get("depType");
        int page = reqMap.get("page");
        int rows = reqMap.get("rows");
        int dep_id = Integer.valueOf(request.getAttribute("dep_id").toString());
        return ResultUtil.success(_depSvs.findbyPageable(depType, dep_id, page, rows));
    }

    @RequestMapping(value = "/city_admin")
    public Msg listCityAdmin() {
        return ResultUtil.success(_depSvs.findByDepTypeAndPidNot(1, 0));
    }

    @RequestMapping(value = "/admin")
    public Msg listPageable1() {
        return ResultUtil.success(_depSvs.findOneById(1));
    }

    @RequestMapping(value = "/city_area")
    public Msg cityAndArea(@RequestBody Map<String, Integer> map) {
        int dep_id = Integer.valueOf(request.getAttribute("dep_id").toString());
        int isall = map.get("id");

        if (isall == 1 && dep_id == 1)// 查询所有级别，包括平台这一级别,超管权限
        {
            Sys_Department admin = _depSvs.findOneById(1);
            List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
            Map<String, Object> plat = new HashMap<String, Object>();
            plat.put("label", admin.getDepName());
            plat.put("value", admin.getId());

            List<Map<String, Object>> cities = _depSvs.findByDepTypeAndTreeRootLike(1, "," + dep_id + ",");
            for (Map<String, Object> mp : cities) {
                List<Map<String, Object>> areas = _depSvs.findByDepTypeAndTreeRootLike(2,
                        "," + mp.get("value").toString() + ",");
                for (Map<String, Object> area : areas) {
                    List<Map<String, Object>> gcs = _gcSvs.findByDepId(Integer.valueOf(area.get("value").toString()));
                    area.put("children", gcs);
                }
                mp.put("children", areas);
            }
            plat.put("children", cities);
            result.add(plat);
            return ResultUtil.success(result);
        } else {
            List<Map<String, Object>> cities = _depSvs.findByDepTypeAndTreeRootLike(1, "," + dep_id + ",");
            for (Map<String, Object> mp : cities) {
                List<Map<String, Object>> areas = _depSvs.findByDepTypeAndTreeRootLike(2,
                        "," + mp.get("value").toString() + ",");
                for (Map<String, Object> area : areas) {
                    List<Map<String, Object>> gcs = _gcSvs.findByDepId(Integer.valueOf(area.get("value").toString()));
                    area.put("children", gcs);
                }
                mp.put("children", areas);
            }
            return ResultUtil.success(cities);
        }

    }

    /**
     * 数据新增或更新，save方法可以执行添加也可以执行更新，如果需要执行持久化的实体存在主键值则更新数据，如果不存在则添加数据。
     */
    @RequestMapping(value = "/save")
    public Msg save(@RequestBody Sys_Department dep) {
        String action = dep.getId() > 0 ? "修改:" : "新增:";
        try {
            Sys_Department d = _depSvs.save(dep);// 插入基本信息
            Sys_Department parent = _depSvs.findOneById(d.getPid());
            if (d.getDepType() == 2) {// 区域 继承上级的省市
                d.setProvince(parent.getProvince());
                d.setCity(parent.getCity());
            }
            if (d.getDepType() == 1 && d.getId() > 0) {// 修改上级省市信息 需要对应修改下级省市信息
                List<Sys_Department> sons = _depSvs.findByDepTypeAndPid(2, d.getId());
                for (Sys_Department son : sons) {
                    son.setProvince(d.getProvince());
                    son.setCity(d.getCity());
                }
                _depSvs.batchSave(sons);
            }
            if (dep.getPid() == 1) {
                d.setTreeRoot(parent.getTreeRoot() + parent.getId() + "," + d.getId() + ",");
            } else {
                d.setTreeRoot(parent.getTreeRoot() + d.getId() + ",");
            }
            d = _depSvs.save(dep);// 需改权限
            if (d != null && d.getId() > 0) {
                String page = "";
                if (d.getDepType() == 1) {
                    page = "部门管理";
                } else {
                    page = "区域管理";
                }
                Sys_Log log = new Sys_Log(getLoginName(), getLocalIp(), page, action + d.getDepName());
                _logSvs.save(log);
                return ResultUtil.success();
            } else {
                return ResultUtil.error(-1, "操作失败，请联系管理员。");
            }
        } catch (DataIntegrityViolationException e) {
            logger.error(e.getMessage());
            if (dep.getDepType() == 1)
                return ResultUtil.error(-1, "部门名称重复。");
            else
                return ResultUtil.error(-1, "区域名称重复。");
        }

    }

    /**
     * 删除设备信息，删除信息后返回剩余信息
     */
    @RequestMapping(value = "/delete")
    public Msg delete(@RequestBody Map<String, Integer> map) {
        int id = Integer.valueOf(map.get("id"));
        Sys_Department g = _depSvs.findOneById(id);
        String page = "";
        if (g.getDepType() == 1) {// 删除部门时不能删除下面的区域
            page = "部门管理";
            List<Sys_Department> areas = _depSvs.findByDepTypeAndPid(2, id);
            if (areas.size() > 0) {
                return ResultUtil.error(-1, "该部门下面存在区域数据，无法删除。");
            }
        } else {
            page = "区域管理";
            Long count = _gcSvs.countByDepartmentId(id);
            if (count > 0) {
                return ResultUtil.error(-1, "该区域下面存在联网单位数据，无法删除。");
            }
        }
        _depSvs.deleteById(id);
        Sys_Log log = new Sys_Log(getLoginName(), getLocalIp(), page, "删除：" + id);
        _logSvs.save(log);
        return ResultUtil.success();
    }

}